package com.momochen.demo.storage;



import com.sun.istack.internal.Nullable;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by momochen on 2016/8/9.
 * 数据存储
 */
public class EcgStorage {
    FileWriter fileWriter = null;//new FileWriter(file.getAbsoluteFile());
    BufferedWriter bufferedWriter = null;//new BufferedWriter(fw);
    //文件路径
    private final String mPath;

    static {
        try {
            File localFile = new File(FileConfig.PROGRAM_ROOT_PATH);
            if (!localFile.exists()) {
                localFile.mkdirs();
            }
        } catch (Throwable localThrowable) {
            localThrowable.printStackTrace();
        }
    }

    public EcgStorage() throws Exception {
        this.mPath = getStorePath();

        fileWriter = createNewFileWriter(mPath);
        this.bufferedWriter = new BufferedWriter(fileWriter);

        //创建配置文件
//        saveDescription();
    }

    /**
     * 获取存储路径
     *
     * @return
     */
    private String getStorePath() {
        return FileConfig.PROGRAM_ROOT_PATH + File.separator + getCurData(false) ;
    }

    /**
     * 获取文件目录
     *
     * @param isTime
     * @return
     */
    private String getCurData(boolean isTime) {
        if (isTime) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            return formatter.format(new Date());
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            return formatter.format(new Date());
        }

    }

    private FileWriter createNewFileWriter(@Nullable String path) throws Exception {
        File localFile = new File(path);

        if (!localFile.exists()) {
            localFile = new File(localFile.getParent());
            if (!localFile.exists()) {
                localFile.mkdirs();
            }
        }
        return new FileWriter(path,true);
    }

    /**
     * 关闭所有资源
     */
    public void close() {
        try {
//            if (outChannelData != null) {
//                this.outChannelData.force(true);
//                this.outChannelData.close();
//                this.outChannelData = null;
//            }

            if(bufferedWriter!=null){
//                bufferedWriter.flush();
                bufferedWriter.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void writeData(String str){
        try {
            bufferedWriter.write(str);
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
